#include <stdio.h>
#include "linkedlist_basic.h"
#include "linkedlist_deletedata.h"

#define NUMELEMENT 10

// Delete all nodes in the list that contain a specific data
void deleteNode(NODE** head, int searchFor) {
	NODE* currentNode = *head;
    NODE* previousNode = NULL;
    NODE* nextNode = currentNode->next;

    // CASE 1: the node is at the head and there is only one node
    if (currentNode->data == searchFor && nextNode == NULL) {
        delete currentNode;
        *head = NULL;
        return;
    }
    
	// CASE 2: any node except the last node
    while (nextNode != NULL) {
        if (currentNode->data == searchFor) {
            delete currentNode;
            // if this is the head of the list
            if (previousNode == NULL) {
                *head = nextNode;
                currentNode = nextNode;
            }
            else {
                previousNode->next = nextNode;
                currentNode = previousNode;
            }
        }        
        previousNode = currentNode;
        currentNode = currentNode->next;
        nextNode = currentNode->next;
    }
    
    // CASE 3: the node is at the end of the list 
    if (currentNode->data == searchFor && nextNode == NULL) {
        delete currentNode;
        previousNode->next = NULL;
    }
}

void test_linklist_deletedata() {
	NODE* head = NULL;
	int data[NUMELEMENT] = {1, 3, 4, 1, 8, 6, 10, 3, 0, 1};
	int number;
	for (int i = 0; i < NUMELEMENT; i++ ) {
		printf("Insert %d at the front of the list\n", data[i]);
		insertInFront(&head, data[i]);
	}
	
	printf("\nTraversing the list\n");
	traverseList(head);
	printf("\n");
	
	number = 1;
	printf("Deleting the nodes that contain data %d\n", number);
	deleteNode(&head, number);
	printf("Traversing the list\n");
	traverseList(head);
	printf("\n");

	number = 3;
	printf("Deleting the nodes that contain data %d\n", number);
	deleteNode(&head, number);	
	printf("Traversing the list\n");
	traverseList(head);
	printf("\n");
}
